<template>
  <el-dialog
    title="选择机器"
    width="400px"
    :close-on-click-modal="false"
    :visible.sync="params.visible"
  >
    <compTree
      ref="tree"
      :tree-show-checkbox="showCheckBox"
      :comp-tree-height="350"
      :show-search="false"
      :show-right-tag="true"
      :tree-default-expanded-keys="treeDefaultExpandedKeys"
      :tree-data="treeData"
    />
    <dialog-btn slot="footer">
      <el-button
        type="primary"
        style="float: left"
        @click="onAgentPlan"
      >选择方案</el-button>
    </dialog-btn>
    <select-agent-plan v-if="selectAgentPlanParams.visible" :params="selectAgentPlanParams" />
  </el-dialog>
</template>

<script>
/**
 * 参数：params: {
 *          sAgentID,
 *          sAgentName,
 *          sMapID,
 *          isNullChecked,
 *          isNullState,
 *          isWindows(可选),
 *          isLinux(可选)
 *      }
 */
import { ParamArr, SQLTable } from '../../../public/js/paramarr'
import Global from '../../../public/js/global'
import MD5 from 'js-md5'
import { getAgentListByCore } from '@/api/core'
import SelectAgentPlan from '@/views/publish/dialog/SelectAgentPlan.vue'
export default {
  name: 'SelectMapAgent',
  components: { SelectAgentPlan },
  props: {
    params: {
      type: Object,
      default() {
        return {
          visible: false,
          sAgentID: '',
          sAgentName: '',
          sMapID: '',
          isNullChecked: false,
          isNullState: false,
          isWindows: false,
          isLinux: false
        }
      }
    }
  },
  data() {
    return {
      treeData: [],
      ttGroup: 1,
      ttAgent: 2,
      showCheckBox: false,
      treeDefaultExpandedKeys: [],
      selectAgentPlanParams: {
        visible: false
      }
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.showCheckBox = this.params.isNullChecked
      const vPar = new ParamArr()
      vPar.setBool('IsAgentParam', false)
      getAgentListByCore(vPar)
        .then((vPar) => {
          const nodes = []
          const nodeMap = new Map()
          let table = new SQLTable(vPar.getTable('k_group'))
          table.first()
          while (!table.eof()) {
            const pnode = Global.getTreeviewPNode(
              nodeMap,
              nodes,
              table.getValueByName('PID')
            )
            const node = {}
            node['sid'] = table.getValueByName('ID')
            node['id'] = node['sid']
            node['sMapID'] = ''
            node['name'] = table.getValueByName('Name')
            node['text'] = node['name']
            node['icon'] = 'wenjianyi'
            node['type'] = this.ttGroup
            pnode.push(node)
            nodeMap.set(node['id'], node)
            table.next()
          }
          table = new SQLTable(vPar.getTable('k_computer'))
          table.first()
          while (!table.eof()) {
            if (
              table.getValueByName('System') === 'Linux' &&
              Boolean(this.params.isWindows) &&
              !this.params.isLinux
            ) {
              table.next()
              continue
            }
            if (
              table.getValueByName('System') !== 'Linux' &&
              Boolean(this.params.isLinux) &&
              !this.params.isWindows
            ) {
              table.next()
              continue
            }
            const pnode = Global.getTreeviewPNode(
              nodeMap,
              nodes,
              table.getValueByName('GroupID')
            )
            const node = {}
            node['sid'] = table.getValueByName('ID')
            node['id'] = node['sid']
            node['sip'] = table.getValueByName('IP')
            node['sMapID'] = ''
            node['name'] = Global.strFormat(
              '{0}[{1}]',
              table.getValueByName('IP'),
              table.getValueByName('Name')
            )
            node['text'] = node['name']
            node['icon'] = Global.getSystemIconStr(
              table.getValueByName('System').trim()
            )
            node['type'] = this.ttAgent
            node['Online'] = table.getValueByName('Online')
            if (node['Online'] === '0') {
              node['tag'] = {
                text: Global.getENStr('离线'),
                effect: 'dark',
                type: 'info'
              }
            } else {
              node['tag'] = {
                text: Global.getENStr('在线'),
                effect: 'dark',
                type: 'success'
              }
            }
            if (node['sid'] === '') node['state'] = { disabled: true }
            pnode.push(node)
            table.next()
          }
          table = new SQLTable(vPar.getTable('k_computer_map'))
          table.first()
          while (!table.eof()) {
            const pnode = Global.getTreeviewPNode(
              nodeMap,
              nodes,
              table.getValueByName('GroupID')
            )
            const node = {}
            node['sid'] = table.getValueByName('ID')
            node['id'] = node['sid']
            node['sip'] = table.getValueByName('IP')
            node['sMapID'] = table.getValueByName('MapID')
            node['name'] = Global.strFormat(
              '{0}[{1}]',
              table.getValueByName('IP'),
              table.getValueByName('Name')
            )
            node['text'] = node['name']
            node['icon'] = Global.getSystemIconStr(
              table.getValueByName('System').trim()
            )
            node['type'] = this.ttAgent
            node['Online'] = table.getValueByName('Online')
            if (node['Online'] === '0') {
              node['tag'] = {
                text: Global.getENStr('离线'),
                effect: 'dark',
                type: 'info'
              }
            } else {
              node['tag'] = {
                text: Global.getENStr('在线'),
                effect: 'dark',
                type: 'success'
              }
            }
            if (node['sid'] === '') node['state'] = { disabled: true }
            pnode.push(node)
            table.next()
          }
          this.treeData = nodes
          // 数据回显
          for (let i = 0; i < nodes.length; i++) {
            if (
              this.params.sAgentID !== '' &&
              this.params.sAgentID.indexOf(nodes[i].sid) !== -1 &&
              nodes[i].sid !== ''
            ) {
              if (this.params.isNullChecked) {
                this.$refs.tree.setChecked(this.treeData[i], true)
              }
            }
            if (
              this.params.sAgentID !== '' &&
              this.params.sAgentID.indexOf(nodes[i].sid) !== -1 &&
              nodes[i].sid !== ''
            ) {
              if (this.params.isNullChecked) {
                this.$refs.tree.setChecked(this.treeData[i], true)
              }
            }
          }
        })
        .catch(() => {})
    },
    onAgentPlan() {
      this.selectAgentPlanParams.visible = true
      this.selectAgentPlanParams.confirm = (params) => {
        this.selectAgentPlanParams.visible = false
        for (let i = 0; i < this.treeData.length; i++) {
          if (params.nodes.indexOf(this.treeData[i].name) !== -1) {
            this.$refs.tree.setChecked(this.treeData[i], true)
          }
        }
      }
    },
    confirm() {
      const outParams = {}
      if (this.params.isNullChecked) {
        const result = this.getResult()
        if (!this.params.isNullState) {
          if (result.sID.toString() === '') {
            return this.$message.warning('请选择在线机器')
          }
        }
        outParams.sAgentID = result.sID.toString()
        outParams.sMapID = result.sMapID.toString()
        outParams.sAgentName = result.sAgentName.toString()
        outParams.sIP = result.sIP.toString()
      } else {
        const node = this.$refs.tree.getCurrentNode()
        if (node === null || node.type === this.ttGroup) {
          return this.$message.warning('请选择机器')
        }
        if (node.sid === '') {
          return this.$message.warning(node.name + '对应代理端不存在')
        }
        outParams.sAgentID = node.sid
        outParams.sMapID = MD5(node.sMapID + node.sip)
        outParams.sAgentName = node.name
      }
      if (this.params.confirm !== undefined) {
        this.params.confirm(outParams)
      } else {
        this.$emit('confirm', outParams)
      }
    },
    getResult() {
      const result = {}
      result.sID = []
      result.sAgentName = []
      result.sMapID = []
      result.sIP = []
      const nodes = this.$refs.tree.getCheckedNodes()
      for (let i = 0; i < nodes.length; i++) {
        switch (nodes[i].type) {
          case 2:
            if (this.params.isNullState) {
              result.sID.push(nodes[i].sid)
              result.sMapID.push(MD5(nodes[i].sMapID + nodes[i].sip))
              result.sAgentName.push(nodes[i].name)
              result.sIP.push(nodes[i].sip)
            } else {
              if (nodes[i].Online === '1') {
                result.sID.push(nodes[i].sid)
                result.sMapID.push(MD5(nodes[i].sMapID + nodes[i].sip))
                result.sAgentName.push(nodes[i].name)
                result.sIP.push(nodes[i].sip)
              }
            }
            break
        }
      }
      return result
    }
  }
}
</script>

<style scoped>
</style>
